import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Util} from "../../../common/util";
import {InterbankService} from "../interbank.service";
import {Observable, Subscribable} from "rxjs/Observable";
import {Subscription} from "rxjs/Subscription";
import {PaginationModel} from "../../../widgets/pagination/pagination.component";

export interface IBTTurnoverSearchModel {
  /**
   * 组合名称
   */
  fundName?: string;
  /**
   * 组合代码
   */
  fundCodeList?: string;
  /**
   * 交发生场所
   */
  tradingFloor?: string;
  /**
   * 发生开始日期
   */
  occurDateBegin?: string;

  /**
   * 发生结束日期
   */
  occurDateEnd?: string;

  /**
   * 当前页码
   */
  page?: number;

  /**
   * 每一页的记录数
   */
  pageSize?: number;

  /**
   * 用户自定义字段
   */
  [propName: string]: any;
}
;

@Component({
  selector: 'interbank-turnover',
  templateUrl: './turnover.component.html',
  styleUrls: ['./turnover.component.scss']
})
export class TurnoverComponent implements OnInit, AfterViewInit {

  /**
   *  组合流水概览视图列表数据
   */
  public overviewListData = [];

  /**
   * 组合流水详细视图列表数据
   */
  public detailListData = [];

  /**
   * 当前分页信息
   */
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  /**
   * 组合流水列表视图状态对象，overview代表概览视图，detail代表详细视图， true表示显示， false表示隐藏
   * @type {{overview: boolean; detail: boolean}}
   */
  public tableViewStatus: { [prop: string]: boolean } = {
    overview: true,
    detail: false
  };

  /**
   * 搜索条件临时缓冲
   * @type {{}}
   */
  public searchConditionCache: IBTTurnoverSearchModel = {};

  @ViewChild('fundCodeList')
  public fundCodeListEl: ElementRef;

  constructor(public service: InterbankService) {
  }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
    this.select2PluginInit().then(() => {
      this.search();
    });
  }

  /**
   * 初始化select2插件搜索下拉框
   */
  public async select2PluginInit() {
    await new Promise((resolve, reject) => {
      this.service.getFundInfoListData().subscribe((data) => {
        data = (data || []).map((item) => {
          return {
            id: item.fundCode,
            text: item.fundName
          };
        });
        const $fundCodeList = Util.$(this.fundCodeListEl.nativeElement).select2({
          data,
          multiple: true,
          closeOnSelect: false
        });
        $fundCodeList.data('select2').$container.css('width', '175px');
        resolve(data);
      });
    });
  }

  /**
   * 获取银行间债券交易列表数据并渲染列表
   * @param backToOnePage
   * @param usesearchConditionCache
   */
  public search(backToOnePage: boolean = false, usesearchConditionCache: boolean = true) {
    const searchCondition: IBTTurnoverSearchModel = this.wrapperSearchModule();
    if (!usesearchConditionCache) {
      this.searchConditionCache = searchCondition;
    }
    if (backToOnePage) {
      this.pageInfo.currentPageNum = 1;
    }
    if (this.tableViewStatus.overview) {
      this.getTurnoverOverviewListData(this.searchConditionCache);
    } else {
      this.getTurnoverDetailListData(this.searchConditionCache);
    }
  }

  /**
   * 将所有搜索条件框重置为空
   */
  public resetSearch() {
    Util.resetInputs(".ibt-search-input");
    this.searchConditionCache = {};
  }

  /**
   * 将用户输入所有搜索值包装成为一个搜索数据模型对象
   * @returns {IBTTurnoverSearchModel}
   */
  public wrapperSearchModule(): IBTTurnoverSearchModel {
    const $ = window["$"];
    const data: IBTTurnoverSearchModel = {};
    $(".ibt-search-input").each((index, item) => {
      const $item = Util.$(item);
      const type = item.type;
      const id = item.id;
      const value = item.value;
      const select2 = $item.data('select2');
      const daterangepicker = $item.data('daterangepicker');
      if (id && id !== "") {
        if (select2 != null) {
          data[id] = $item.select2('val');
        } else if (daterangepicker != null) {
          data[`${id}Begin`] = (value != null && value.length > 0 ) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`${id}End`] = (value != null && value.length > 0 ) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else {
          if (type === 'text' || type === 'select' || type === 'select-one') {
            data[id] = value;
          } else if (type === 'checkbox') {
            data[id] = item.checked ? value : "";
          }
        }
      }
    });
    return data;
  }

  /**
   * 获取组合流水概览视图列表数据
   * @param search
   * @param pageNum
   * @param pageSize
   * @returns {Subscription}
   */
  public getTurnoverOverviewListData(search: IBTTurnoverSearchModel,
                                     pageNum: number = this.pageInfo.currentPageNum,
                                     pageSize: number = this.pageInfo.pageSize): Subscription {
    search.page = pageNum;
    search.pageSize = pageSize;
    return this.service.getTurnoverOverviewListData(search).subscribe((data) => {
      this.overviewListData = data.list;
      this.pageInfo.startRow = data.startRow;
      this.pageInfo.endRow = data.endRow;
      this.pageInfo.total = data.total;
      this.pageInfo.totalPages = data.pages > 0 ? data.pages : 1;
      this.pageInfo.currentPageNum = data.pageNum > 0 ? data.pageNum : 1;
    });
  }

  /**
   * 获取组合流水详细视图列表数据
   * @param search
   * @param pageNum
   * @param pageSize
   * @returns {Subscription}
   */
  public getTurnoverDetailListData(search: IBTTurnoverSearchModel,
                                   pageNum: number = this.pageInfo.currentPageNum,
                                   pageSize: number = this.pageInfo.pageSize): Subscription {
    search.page = pageNum;
    search.pageSize = pageSize;
    return this.service.getTurnoverDetailListData(search).subscribe((data) => {
      this.detailListData = data.list;
      this.pageInfo.startRow = data.startRow;
      this.pageInfo.endRow = data.endRow;
      this.pageInfo.total = data.total;
      this.pageInfo.totalPages = data.pages > 0 ? data.pages : 1;
      this.pageInfo.currentPageNum = data.pageNum > 0 ? data.pageNum : 1;
    });
  }

  /**
   * 切换到概览视图
   */
  public switch2Overview(): void {
    this.tableViewStatus.overview = true;
    this.tableViewStatus.detail = false;
    this.resetSearch();
    this.search(true);
  }

  /**
   * 切换到详细视图
   */
  public switch2Detail(): void {
    this.tableViewStatus.overview = false;
    this.tableViewStatus.detail = true;
    this.resetSearch();
    this.search(true);
  }

  /**
   * 根据页码请求查询相关基金配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.search();
  }

  /**
   * 改变每页显示记录数
   * @param pageSize
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.search(true);
    }
  }
}

